import { moment } from "/utils/core";
import request from "/utils/omsRequest";
import { provinceCityArea, salerSelect } from "/utils/mixins";
import validator from "/utils/validators";
import { showToast } from "/utils/common";

const app = getApp();

Component({
  mixins: [provinceCityArea, salerSelect],
  data: {
    userInfo: null,
    dingOrgIndex: null,
    dingUserIndex: null,
    areaIndexs: [],
    shopList: [],
    form: {
      name: "", // 商户名称
      categoryId: "", // 商户分类
      provinceId: null, // 省
      cityId: null, // 市
      districtId: null, // 区
      detailAddress: "", // 详细地址
      contacts: "", // 联系人
      contactsPhone: "", // 联系电话
      dingOrgId: null, // 机构id
      dingUserId: null,
      privateOrPublic: null, //商户性质
      legalPerson: "", // 法人
      certificateDate: "", // 证件有效日期
      certificateType: "IDENTITY_CARD", // 证件类型
      certificate: "", // 证件号
      businessLicense: "", // 营业执照号
      businessLicenseName: "", // 营业执照名
      businessDate: "", // 营业执照有效期
      enclosure: null
    },
    categoryValue: [], // 商户分类列表数据绑定
    orgList: [],
    dingUserList: [],
    visibleCategoryPicker: false,
    categorys: []
  },
  props: {
    id: null,
    onSubmit: () => { }
  },
  async didMount() {
    this.setData({
      userInfo: app.globalData.userInfo
    });
    dd.showLoading({
      content: '加载中...',
    });
    this.onStoreInit()
    await request({
      url: "/ajax/dianpingMerchantCategory/tree"
    }).then(res => {
      this.setData({
        categorys: res.voList
      })
    });
    if (this.props.id) {
      request({
        url: "/ajax/merchant/findMerchant",
        data: {
          id: +this.props.id
        }
      }).then(res => {
        dd.hideLoading();
        res.vo.dingOrgId = +res.vo.dingOrgId;
        Object.assign(this.data.form, res.vo)
        this.setData({
          form: this.data.form
        });
        // 商户类别回显
        this.data.categoryValue = this.diplayMerchantClassifiy(this.data.categorys, this.data.form.categoryId)
        this.setData({
          categoryValue: this.data.categoryValue
        });
        this.data.dingOrgIndex = this.data.orgList.findIndex(item => item.id === this.data.form.dingOrgId);
        if (this.data.dingOrgIndex !== -1 && this.data.dingOrgIndex !== null) {
          // 机构&销售回显
          this.onDingOrgChange({ detail: { value: this.data.dingOrgIndex } }, this.data.form.dingUserId);
        }
        if (this.data.form.provinceId === null) {
          this.setData({
            areaIndexs: []
          })
        } else {
          this.data.areaIndexs[0] = this.data.citys.findIndex(item => item.id === this.data.form.provinceId);
          this.getCityData({
            areaId: this.data.citys[this.data.areaIndexs[0]].id,
            type: 1
          }).then(res => {
            this.data.citys[this.data.areaIndexs[0]].children = res.voList;
            this.data.areaIndexs[1] = res.voList.findIndex(item => item.id === this.data.form.cityId);
            this.getCityData({
              areaId: this.data.citys[this.data.areaIndexs[0]].children[this.data.areaIndexs[1]].id,
              type: 2
            }).then(res => {
              this.data.citys[this.data.areaIndexs[0]].children[this.data.areaIndexs[1]].children = res.voList;
              this.data.areaIndexs[2] = res.voList.findIndex(item => item.id === this.data.form.districtId);
              this.setData({
                areaIndexs: this.data.areaIndexs,
                citys: this.data.citys
              })
            })
          });
        }
      })
    }
    dd.hideLoading();
  },
  didUpdate() { },
  didUnmount() { },
  methods: {
    // 商户分类回显
    diplayMerchantClassifiy(list, categoryId) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].id === categoryId) {
          return [i];
        } else {
          if (list[i].children.length) {
            let result = this.diplayMerchantClassifiy(list[i].children, categoryId);
            if (Array.isArray(result)) {
              result.unshift(i);
              return result;
            }
          }
        }
      }
    },
    showDatePicker(e) {
      dd.datePicker({
        format: 'yyyy-MM-dd',
        currentDate: moment().format('YYYY-MM-DD'),
        success: (res) => {
          if (res.date) {
            this.data.form[e.target.dataset.key] = res.date;
            this.setData({
              form: this.data.form
            });
          }
        },
      });
    },
    onCategoryClose() {
      this.setData({
        visibleCategoryPicker: false
      })
    },
    showCategorySelector() {
      this.setData({
        visibleCategoryPicker: true
      })
    },
    onCategoryChange(data) {
      if (data.length === 1) {
        this.data.form.categoryId = this.data.categorys[data[0]].id;
      } else {
        this.data.form.categoryId = this.data.categorys[data[0]].children[data[1]].id;
      }
      this.setData({
        categoryValue: data,
        form: this.data.form
      });
      this.onCategoryClose()
    },
    onProvinceCityChange(arr, [provinceId, cityId, areaId]) {
      this.setData({
        areaIndexs: arr,
        "form.provinceId": provinceId,
        "form.cityId": cityId,
        "form.districtId": areaId,
        visibleProvinceCityPicker: false
      })
    },
    async onDingOrgChange(e, dingUserId) {
      this.setData({
        dingOrgIndex: this.data.orgList.length > 0 ? e.detail.value : null,
        "form.dingOrgId": this.data.orgList.length > 0 ? this.data.orgList[e.detail.value].id : null
      })
      let res = await request({
        url: "/ajax/user/dingUser",
        data: {
          departmentId: this.data.orgList[e.detail.value].id
        }
      })
      this.setData({
        dingUserList: res.voList
      })
      if (dingUserId) {
        this.data.dingUserIndex = res.voList.findIndex(item => item.userid === dingUserId)
        this.setData({
          dingUserIndex: this.data.dingUserIndex
        })
      }
      return res;
    },
    onDingUserChange(e) {
      this.setData({
        dingUserIndex: this.data.dingUserList.length > 0 ? e.detail.value : null,
        "form.dingUserId": this.data.dingUserList.length > 0 ? this.data.dingUserList[e.detail.value].userid : null
      })
    },
    onMerchantNatureChange(e) {
      this.setData({
        "form.privateOrPublic": e.detail.value
      })
    },
    setEffectForever(e) {
      this.data.form[e.target.targetDataset.key] = "2200-12-12";
      this.setData({
        form: this.data.form
      })
    },
    onFileChange(files) {
      this.setData({
        "form.enclosure": files[0]
      })
    },
    onFileRemove(index) {
      this.setData({
        "form.enclosure": null
      })
    },
    updateStore(store) {
      return new Promise((resolve, reject) => {
        dd.showLoading({
          content: '加载中...',
        });
        request({
          url: "/ajax/shop/updateShop",
          method: "post",
          data: store.form,
          headers: {
            "Content-Type": "application/json;utf-8"
          }
        }).then(res => {
          dd.hideLoading();
          showToast({
            type: "success",
            msg: "更新成功"
          });
          resolve()
        }).catch((err) => {
          reject(err);
        });
      })
    },
    // 门店提交
    onStoreFormSubmit(store) {
      return new Promise((resolve, reject) => {
        this.updateStore(store).then(() => {
          resolve();
        }).catch((err) => reject(err));
      })
    },
    onStoreInit() {
      dd.showLoading({
        content: '加载中...'
      })
      request({
        url: "/ajax/shop/list",
        data: {
          merchantId: this.props.id
        }
      }).then(res => {
        dd.hideLoading()
        this.setData({
          shopList: res.voList
        })
      })
    },
    onFormSubmit(e) {
      Object.assign(this.data.form, e.detail.value);
      let validate = new validator();
      validate.add("checkEmpty", this.data.form.name, "商户名称不能为空");
      validate.add("checkEmpty", this.data.form.categoryId, "商户分类不能为空");
      validate.add("checkEmpty", this.data.form.districtId, "联系地址不能为空");
      validate.add("checkEmpty", this.data.form.detailAddress, "详细地址不能为空");
      validate.add("checkEmpty", this.data.form.contacts, "联系人不能为空");
      validate.add("checkPhoneNumber", this.data.form.contactsPhone, "手机号码不符合规则");
      validate.add("checkEmpty", this.data.form.dingOrgId, "所属机构不能为空");
      validate.add("checkEmpty", this.data.form.dingUserId, "所属销售不能为空");
      validate.add("checkEmpty", this.data.form.legalPerson, "法人不能为空");
      validate.add("checkEmpty", this.data.form.privateOrPublic, "商户性质不能为空");
      if (this.data.form.privateOrPublic === 1) {
        validate.add("checkEmpty", this.data.form.certificateType, "证件类型不能为空");
        validate.add("checkEmpty", this.data.form.certificate, "证件号不能为空");
      } else if (this.data.form.privateOrPublic === 2) {
        validate.add("checkEmpty", this.data.form.businessLicense, "营业执照号不能为空");
        validate.add("checkEmpty", this.data.form.businessLicenseName, "营业执照名称不能为空");
        validate.add("checkEmpty", this.data.form.enclosure, "营业执照图片不能为空");
      }
      if (validate.check()) {
        this.props.onSubmit(this.data.form);
      }
    }
  },
});
